<?php

namespace common\models\info;

use common\component\BaseActiveRecord;
use common\component\Constant;
use common\utils\CommonUtil;
use Yii;
use yii\base\Exception;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "{{%info_category}}".
 *
 * @property int $id
 * @property string $cate_name 分类名称
 * @property int $status 状态
 * @property int $updated_at
 * @property int $created_at
 */
class Category extends BaseActiveRecord
{
    const STATUS_DISABLE = 0;   //禁用
    const STATUS_ENABLE = 1;    //启用

    static $statusArr = [
        self::STATUS_ENABLE => '启用',
        self::STATUS_DISABLE => '禁用',
    ];

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{zt_category}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['updated_at', 'created_at','status'], 'integer'],
            [['cate_name'], 'string', 'max' => 32],
            ['cate_name','trim']
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => '序列',
            'cate_name' => '分类名称',
            'status'=>'状态',
            'updated_at' => '修改时间',
            'created_at'=>'创建时间',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at'],
                    self::EVENT_BEFORE_UPDATE => ['updated_at']
                ]
            ]
        ];
    }

    /**
     * 保存数据之前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }
        if ($insert) {
            if (static::find()->where(['!=', 'id', $this->id])->exists()) {
                $this->addError("cate_name", "【" . $this->cate_name . "】已存在");
                return false;
            }
        } else {
          //  var_dump($this->id);
           // die();
            $where_one = ['and'];
            $where_one[] = ['=','cate_name',$this->cate_name];
            $where_one[] = ['!=','id',$this->id];
            if (static::find()->where($where_one)->exists()) {
                $this->addError("tag_name","【".$this->cate_name."】已存在");
                return false;
            }
        }
        return true;
    }

    public function afterFind()
    {
        parent::afterFind();
        $this->ui();
    }
    public function ui() {
        $this->ui["status"] = self::$statusArr[$this->status];
        $this->ui["cate_name"] = $this->cate_name;
        $this->ui["created_at"] = date("Y-m-d H:i:s",$this->created_at);
        $this->ui["updated_at"] = date("Y-m-d H:i:s",$this->updated_at);
        $this->ui["id"] = $this->id;
    }

    /**
     * 实例化模型对像
     * @param $id
     * @return BaseActiveRecord|null|static
     */
    public static function modelById($id) {
        if (!$id) {
            $model = new self();
        }
        else {
            $model = static::findOne($id);
        }
        return $model;
    }

    public function dataListTable($post) {
        //请求参数组装
        $where = ["and"];

        if (!empty($post['cate_name'])) {
            $where[] = ['like','cate_name',trim($post['cate_name'])];
        }
        if (isset($post['status']) && $post['status'] == -1) {
            $where[] =['=','status',-1];
        } else {
            //删除的状态不显示在列表中
            $where[] = ['>','status',-1];
        }
        $query = self::find()->where($where);
        $dataArr = self::table($query,$post);
        return $dataArr;
    }

    /**
     * @param $id
     * @return bool|false|int
     */
    public function clearRecycle($id) {
        if ($id) {
            $model = self::findOne($id);
            if (!$model) {
                $this->addError('id',"分类不存在");
                return false;
            }
            return $model->delete();
        } else {
            return static::deleteAll(["status"=>-1]);
        }
    }

    /**
     * 将状态为-1 改为 0
     * @param $id
     * @return bool|int
     */
    public function undoCategory($id) {
        $model = self::find()->where("id=:id AND status=:status",[":id"=>$id,":status"=>-1])->one();
        if (!$model) {
            $this->addError("id","分类不存在，无法还原");
            return false;
        }
        return $model->updateAttributes(['status'=>0]);
    }

    /**
     * 获取文章分类
     * @param $cate_id
     * @param $flag
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public static function getArticleCateData($cate_id,$flag=false) {
        $data = [];
        if (!$data || !$flag) {
            $where = ['in','id',explode(',',$cate_id)];
            $data = static::find()->where($where)->asArray()->all();
            $data = $data?array_column($data,'cate_name'):[];
        }
        return $data;
    }

    public static function getFieldById($id,$field="cate_name") {
        $data = self::loadRowData($id);
        return $data[$field]?$data[$field]:"";
    }

    public static function getFieldByIds($ids,$field="cate_name") {
        $data = self::loadRowDataArr($ids);
        return array_column($data,$field)?implode(",",array_column($data,$field)):"";
    }


    public static function loadRowData($id) {
        $data  =[];
        if (!$data) {
            $data = static::find()->where(["id"=>$id])->asArray()->one();
        }
        return $data;
    }

    public static function loadRowDataArr($ids) {

        $where = ['and'];
        $where[] = ['in','id',$ids];
        return static::find()->where($where)->asArray()->all();

    }
    public static function findAll($condition)
    {
        return self::find()->asArray()->all();
    }
}
